package com.study.shiro.controller;

import com.study.shiro.common.RestResult;
import com.study.shiro.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @author huang guang yue
 * @version v1.0.0
 * @date 2021 2021/3/18 16:49
 */
@RequestMapping("/pub")
@RestController
public class PubController {

    @Autowired
    private IUserService userService;

    @GetMapping("/need_login")
    public RestResult<Object> needLogin(){
        return RestResult.error(-2, "请登陆");
    }

    @GetMapping("/not_perm")
    public RestResult<Object> notPerm(){
        return RestResult.error(-3, "没有权限");
    }

    @PostMapping("/login/{username}/{pwd}")
    public RestResult<Object> login(@PathVariable String username, @PathVariable String pwd){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, pwd);
        try {
            subject.login(usernamePasswordToken);
            return RestResult.success("登陆成功", new HashMap<String, Object>(2) {{
                put("sessionId", subject.getSession().getId());
            }});
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return RestResult.error("登陆失败");
        }
    }

    @GetMapping("/user/id/{userId}")
    public RestResult<Object> roleAndPerm(@PathVariable Long userId){
        return RestResult.success(userService.listRoleAndPermsByUserId(userId));
    }

    @GetMapping("/user/name/{username}")
    public RestResult<Object> roleAndPermByUsername(@PathVariable String username){
        return RestResult.success(userService.listRoleAndPermsByUsername(username));
    }

}
